/*  
=========================================================
  Options:
  veh = [base, [<startOpts>], [<Pilot Options>], [<CoPilot Options>] , [<target list>], <ondemand>, <haveAgent>, <agentOptions>] execVM "transportation\initHeli.sqf"
  
  Parameters:

  TES_startMarkerPos: Marking the position where Heli will start

  base: object (helipad) where will be based (and first waypoint when ondemand=false or if flying = false)  
  
  startOpts: [<flying>]
  	
  Pilot Options:  [<Pilot stanza>,<Pilot parameter>] -- Default ["ONBOARD",null]
	Pilot stanza: "ONBOARD", "STAND" ,"SIT"
	Pilot parameter:  
					For "SIT" stanza = chair object
					Not used for "ONBOARD", "STAND"
  
  Note:If CoPilot is empty [] then no CoPilot will be spawned -- Default [] (No coPilot)
  CoPilot Options:  [<CoPilot stanza>,<CoPilot parameter>]
	CoPilot stanza: "ONBOARD", "STAND" , "SIT"
	CoPilot parameter:  
					For "SIT" stanza = char object
					Not used for "ONBOARD", "STAND"
  
  target list: List of targets [[<helipad object>,"Name of target"],...]
  
  ondemand:	if TRUE heli will only respwan when called. if FALSE will respwan on start and when die.
  
  haveAgent: 
  
  agentOptions: 
 
  Default values of all settings are:
  ....
  
=========================================================
*/
#include "macros.sqf"
waitUntil {!isNil "TES_init_started"};
if (!isServer) exitWith {};
/* ========================================================= */
// Define Preferences
_heliTypes =["ibr_as350_civ"];
_heliPilots =["Pilot"];
_heliCoPilot =["Poet_PMC","Dixon_PMC"];
_defaultPilotStanza = "ONBOARD";
_deserted = 360; //Seconds Heli need to be deserted before respawn
/* ========================================================= */
/*           Dont change this point bellow                   */
/* ========================================================= */
// Some Macros
#define GetRandomElem(_myarray) _myarray select (random (count _myarray - 1))
/* ========================================================= */
// Define variables
_helibaseMarker = _this select 0; // "_this" is the market where script is called.. use only the Position
_startOpts = if (count _this > 1) then {_this select 1} else {[true]};
_pilotOptions = if (count _this > 2) then {_this select 2} else {[_defaultPilotStanza]};
_coPilotOptions = if (count _this > 3) then {_this select 3} else {[]};
_targetMarkers = if (count _this > 4) then {_this select 4} else {[]};
_ondemand = if (count _this > 5) then {_this select 5} else {false};
_haveAgent = if (count _this > 6) then {_this select 6} else {false};
_agentOptions = if (count _this > 7) then {_this select 7} else {[]};

_startFlying = if (count _startOpts > 0) then {_startOpts select 0} else {false};

_dir = getDir _helibaseMarker;
_position = GVAR(startMarkerPos);
_pilotStanza = _pilotOptions select 0;
_pilotStanzaOpts = if (count _pilotOptions > 1) then {_pilotOptions select 1} else {null};
_coPilotStanza = if (count _coPilotOptions > 0) then {_coPilotOptions select 0} else {null};
_coPilotStanzaOpts = if (count _coPilotOptions > 1) then {_coPilotOptions select 1} else {null};
_haveCoPilot  = if (count _coPilotOptions > 0) then {true} else {false};

/* ========================================================= */
_mygroup = createGroup civilian;
/* ========================================================= */		
// Start monitoring the vehicle
_timeout = time + _deserted;
_firsttime=true;
_run=true;
_isWaiting=false;
_unit=null;
_hasRequested = false;
_helipilot = null;

while {_run} do 
{	
	if (!(_firsttime)) then { sleep (1 + random 2);};
	/* =================== Firt Time or Dead =================== */	
	if ( (_firsttime) ) then { // Firtime = init all stuff
		//hintsilent format["INIT"];
		_firsttime=false;
		_dead = false;
		// Heli
		if (_startFlying) then {
			_unit = createVehicle [GetRandomElem(_heliTypes), _position, [], 0, "FLY"];
			[_unit, [position  _helibaseMarker], 50, true] call FUNC(heliRoute); //execVM "transportation\mando_heliroute_arma.sqf";
		} else {
			_position = position _helibaseMarker;
			_unit = createVehicle [GetRandomElem(_heliTypes), _position, [], 0, "NONE"];
			_unit setVariable ["mando_heliroute", "waiting"];
		};
		[_unit] join _mygroup ;
		_unit setDir _dir;
		/* ========================== Pilot ======================== */	
		_helipilot = _mygroup createUnit [GetRandomElem(_heliPilots), getPos _unit, [], 5, "NONE"]; // Pilot
		switch (true) do {
			case (_pilotStanza == "ONBOARD" or _startFlying ): { 
				[_helipilot] join _mygroup ;
				_helipilot moveindriver _unit;
				_helipilot  assignAsDriver _unit; 
				//[_helipilot] orderGetIn true;
			};
			case (_pilotStanza == "STAND"): { 
				[_helipilot] join _mygroup ;
			};
			case (_pilotStanza == "SIT"): { 
				[_helipilot] join _mygroup ;
			};
		};
		/* ======================== CoPilot ======================== */	
		// [_unit] execVM "transportation\initAgent.sqf";
		/* =====================  Start Flying ===================== */	
		if (_startFlying) then {
			_unitinit = "[_unit, [position _helibaseMarker], 80, true] execVM 'transportation\mando_heliroute_arma.sqf'";
			_unit setVehicleInit format ["%1;", _unitinit];
			processInitCommands;
			//[_unit, [position _helibaseMarker], 80, true] call FUNC(heliRoute);
			// _unit setVariable ["mando_heliroute", "busy"];
		} else {
			_unit setVariable ["mando_heliroute", "waiting"];
		};
		_unit setVariable ["taxi_status", "busy"];
		// if Dead will start allways flying (no ugly respwans)
		_position = GVAR(startMarkerPos);
		_startFlying = true;
	};
	/* ========================================================= */		
    // if ((getDammage _unit > 0.8) and ({alive _x} count crew _unit == 0)) then {_dead = true}; // crew may not be onboard

	// Check if the vehicle is deserted.
	if (_deserted > 0 and false) then //Dont check for now... crew may not be onboard
	{
		if ((getPosASL _unit distance _position > 10) and ({alive _x} count crew _unit == 0) and (getDammage _unit < 0.8)) then 
		{
			if ({alive _x} count crew _unit > 0) then {_dead = false}; 
			if ({alive _x} count crew _unit == 0) then {_dead = true; _nodelay =true}; 
			if !(alive _unit) then {_dead = true; _nodelay = false}; 
		};
	};

    if (_dead) then 
	{	
		//if (_nodelay) then {sleep 0.1; _nodelay = false;} else {sleep _delay;};
		//if (_dynamic) then {_position = getPosASL _unit; _dir = getDir _unit;};
		//if (_explode) then {_effect = "M_TOW_AT" createVehicle getPosASL _unit; _effect setPosASL getPosASL _unit;};
		//sleep 0.1;
		//{ deleteVehicle _x } forEach (crew _unit); deleteVehicle _unit;
/*
		if (_haveinit) then 
					{_unit setVehicleInit format ["%1;", _unitinit];
					processInitCommands;};
		if (_hasname) then 
					{_unit setVehicleInit format ["%1 = this; this setVehicleVarName ""%1""",_unitname];
					processInitCommands;};
*/
	};
	if (_isOnTarget) then { //No Use !!!???
		_unit land "LAND";
	};
	/* ================= Pilot/CoPilot Animations ============== */		
	if (_unit getVariable "mando_heliroute" == "waiting" and !_isWaiting and _unit getVariable "taxi_status" == "busy") then {
		switch (true) do {
			case (_pilotStanza == "ONBOARD"): { 
				_isWaiting=true;
			};
			case (_pilotStanza == "STAND" or _pilotStanza == "SIT" ): { 
				// Do animation
				//_helipilot leaveVehicle _unit;
				[_helipilot] orderGetIn false;
				_isWaiting=true;
			};
		};
	};
	if (_isWaiting) then {
		if (!_haveCoPilot and !_haveAgent) then {
			[_helipilot, _targetMarkers, _unit]  execVM "transportation\addActions.sqf";
		};		
		_unit setVariable ["taxi_status", "free"];
		_isWaiting = false;
	};
	if (_unit getVariable "taxi_status" == "request") then {
		[_helipilot]  execVM "transportation\clearActions.sqf";
		_unit setVariable ["taxi_status", "busy"];
		_helipilot  assignAsDriver _unit; 
		[_helipilot] orderGetIn true;
		//hint format ["dist %1" ,(_helipilot distance (getPos _unit))];
		while {alive _helipilot and !(_helipilot in crew _unit)} do {sleep 0.2};
		if (alive _helipilot) then {
			sleep 1;
			[_unit] call FUNC(heliTakeOff); // execVM "transportation\heliTakeOff.sqf";
			while {(getPosATL _unit select 2) < 5} do {sleep 0.5};
			[_unit, [position (_unit getVariable "taxi_request")], 80, true] call FUNC(heliRoute); //execVM "transportation\mando_heliroute_arma.sqf";
		}
	};
	//hintsilent format["%7 == %1 -> %2 -> %3 -> %4 -> %5 -> %6 ",_dead ,_cur_idx + 1,_next_idx + 1,count _locs, getPosATL _unit distance _next_pos, _target_done ,_cc];
};